/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.zookeeper.server;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.persistence.Util;

/**
 * this class is used to clean up the 
 * snapshot and data log dir's. This is usually
 * run as a cronjob on the zookeeper server machine.
 * Invocation of this class will clean up the datalogdir
 * files and snapdir files keeping the last "-n" snapshot files
 * and the corresponding logs.
 */
public class PurgeTxnLog {
    private static final Logger LOG = LoggerFactory.getLogger(PurgeTxnLog.class);

    static void printUsage(){
        System.out.println("PurgeTxnLog dataLogDir [snapDir] -n count");
        System.out.println("\tdataLogDir -- path to the txn log directory");
        System.out.println("\tsnapDir -- path to the snapshot directory");
        System.out.println("\tcount -- the number of old snaps/logs you want to keep");
        System.exit(1);
    }
    
    /**
     * 清除快照和日志，保留最后 默认3 个快照和相应的日志.
     *
     * 1. 1~10000条数据，在这个事务日志文件01里,
     * 2. 切换事务日志文件成为日志文件02，以后的事务日志都写到事务日志文件02里去，从10001条开始
     * 3. 同时写一份数据快照，包含了1~10000条事务对应的一份内存文件目录树，叫做数据快照01，包含了1~10000条事务更新后对应的文件目录树。
     * 4. 10001~20000条数据，在这个事务日志文件02里,
     * 5. 切换事务日志文件成为事务日志文件03，以后的事务日志都写到事务日志文件03里去，从20001条开始
     * 6. 同时写一份数据快照，包含了1~20000条事务对应的一份内存文件目录树，叫做数据快照02，包含了1~20000条事务更新后对应的文件目录树。
     *
     * @param dataDir 包含日志的目录
     * @param snapDir 包含快照的目录
     * @param num 要保留的快照数
     * @throws IOException
     */
    public static void purge(File dataDir, File snapDir, int num) throws IOException {
        // 保留的snapshot数量必须超过3
        if (num < 3) {
            throw new IllegalArgumentException("count should be greater than 3");
        }

        // 校验并创建数据文件（事务）对象和快照文件对象
        FileTxnSnapLog txnLog = new FileTxnSnapLog(dataDir, snapDir);
        Set<File> exc=new HashSet<>();
        // 发现最近的快照文件
        List<File> snaps = txnLog.findNRecentSnapshots(num);
        if (snaps.size() == 0) {
            return;
        }
        File snapShot = snaps.get(snaps.size() -1);
        for (File f: snaps) {
            exc.add(f);
        }

        // 最后要保留的快照zxid
        long zxid = Util.getZxidFromName(snapShot.getName(),"snapshot");
        // 添加不用保留的数据文件
        exc.addAll(Arrays.asList(txnLog.getSnapshotLogs(zxid)));

        final Set<File> exclude = exc;

        class MyFileFilter implements FileFilter{
            private final String prefix;

            MyFileFilter(String prefix){
                this.prefix=prefix;
            }

            @Override
            public boolean accept(File f){
                if(!f.getName().startsWith(prefix)
                            || exclude.contains(f)) { // 如果保存表示需要过滤
                    return false;
                }
                return true;
            }
        }

        // 列举需要删除的数据文件列表
        List<File> files=new ArrayList<>(Arrays.asList(txnLog.getDataDir().listFiles(new MyFileFilter("log."))));
        // 列举需要删除的快照文件列表
        files.addAll(Arrays.asList(txnLog.getSnapDir().listFiles(new MyFileFilter("snapshot."))));

        //进行删除
        for(File f: files){
            System.out.println("Removing file: "+ DateFormat.getDateTimeInstance().format(f.lastModified())+ "\t"+f.getPath());
            if(!f.delete()){
                System.err.println("Failed to remove "+f.getPath());
            }
        }

    }
    
    /**
     * @param args PurgeTxnLog dataLogDir
     *     dataLogDir -- txn log directory
     *     -n num (number of snapshots to keep)
     */
    public static void main(String[] args) throws IOException {
        if(args.length<3 || args.length>4) {
            printUsage();
        }
        int i = 0;
        File dataDir=new File(args[0]);
        File snapDir=dataDir;
        if(args.length==4){
            i++;
            snapDir=new File(args[i]);
        }
        i++; i++;
        int num = Integer.parseInt(args[i]);
        purge(dataDir, snapDir, num);
    }
}
